import jwt
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from starlette.requests import Request

from FastApi import ErrorCode
from FastApi.Database import GetDb
from FastApi.Schemas.UserTokenSchema import UserModel
from FastApi.UtilsWeb import Result

user_router = APIRouter()


@user_router.post("/login")
async def login(user_name: str, user_pass: str, db: Session = Depends(GetDb)):
    user_model = UserModel()
    res_user = user_model.LoginByUserNameAndPwd(db, user_name, user_pass)
    return Result(res_user, "登陆成功", ErrorCode.USER_OR_PASS_ERROR, "用户名或密码错误")


@user_router.get("/index")
async def index(db: Session = Depends(GetDb)):
    data = db.query(UserModel).filter(UserModel.id == 1).first()
    print(data)
    return {data}


@user_router.get('/oauth/{token}')
async def oauth(token: str, request: Request, db: Session = Depends(GetDb)):
    # 设备 和 token 验证
    header = request.headers
    header_device = header['X-Device']
    # if not header_device == "app": return Error(ErrorCode.DEVICE_MATCH_ERROR, "设备不正确，请选用app登陆")
    # header_token = header['X-token']

    # 根据token获取用户信息
    # res_user_info = UserTokenModel().GetUserInfo(header_token, header_device, db)
    # print(res_user_info)

    data = jwt.decode(token, "JWT_KEY", algorithms=['HS256'])
    address = data['address']
    return {"host": address[0], "port": address[1]}
    return templates.TemplateResponse("oauth.html", {"request": request, "host": address[0], "port": address[1]})


user_controller = user_router
